﻿/**
 * 通信组件对象
 */
var socket = undefined;

jQuery(document).ready(function () {
    /**
     * 设置当前的用户名
     */
    jQuery("#userName").val(Common.GetRandomName());

    /**
     * 新建一个通信组件对象
     */
    socket = new BaseCommunication({
        OnTextMessageReceived: function (sendId, message) {
            var sendUserInfo = socket.GetUserById(sendId);
            var strHtml =
                '<div class="chat-message">' +
                    '<img class="message-avatar" src="../Images/TouXiang.jpg" alt="">' +
                    '<div class="message">' +
                    '<a class="message-author" href="#" onclick=\'setChatingUser("' +
                    sendUserInfo.Id +
                    '")\'> ' +
                    sendUserInfo.Name +
                    "</a> 对你说：" +
                    '<span class="message-date"> ' +
                    Common.DateFormat(new Date(), "yyyy-MM-dd hh:mm:ss") +
                    " </span>" +
                    '<span class="message-content">' +
                    message +
                    "</span>" +
                    "</div>" +
                    "</div>";
            $("#divMessages").append(strHtml);
            gotoEnd();
        },
        OnOwnUserInfoReceived: function (myId) {
            console.log(myId);
            alert("发送用户信息成功，正在请求联系人列表……");
            socket.SendRequestUsersMessage();
        },
        OnNewUserConnected: function (userInfo) {
            var strHtml = '<div id="' +
                userInfo.Id +
                '" class="chat-user">' +
                '<img class="chat-avatar" src="../Images/TouXiang.jpg" alt="">' +
                '<div class="chat-user-name">' +
                '<a href="#" onclick="setChatingUser(\'' +
                userInfo.Id +
                '\')">' +
                userInfo.Name +
                "</a>" +
                "</div>" +
                "</div>";
            $("#divUsers").append(strHtml);
        },
        OnUserOffline: function (userInfo) {
            $("#" + userInfo.Id).remove();
            if (chatingUserId != undefined && chatingUserId === userInfo.Id) {
                var user = socket.GetUserById(chatingUserId);
                if (user == undefined) {
                    chatingUserId = undefined;
                    $("#divUserChating").empty();
                }
            }
        },
        OrtherMessageReceived: function (message) {
            console.log(message);
            alert("收到未知的消息！请按 F12 查看！");
        },
        OnClosed: function (e) {
            console.log(e);
            alert("通信程序已经关闭！");
            $("#divUsers").empty();
            $("#divMessages").empty();
            $("#divUserChating").empty();
        },
        SendUserInfoError: function () {
            alert("发送用户信息失败！");
        },
        SendTextMessageError: function (info) {
            alert("发送文本消息或广播消息失败！\r\n" + info);
        },
        SendRequestUsersMessageError: function () {
            alert("请求用户列表失败！");
        },
        BroadcastTextMessageReceived: function (sendId, message) {
            var user = socket.GetUserById(sendId);
            var htmlStr1 =
                '<div class="chat-message">' +
                    '<img class="message-avatar" src="../Images/TouXiang.jpg" alt="">' +
                    '<div class="message">' +
                    '<a class="message-author" href="#" onclick=\'setChatingUser("' +
                    user.Id +
                    '")\'> ' +
                    user.Name +
                    "</a> 对所有人说：" +
                    '<span class="message-date"> ' +
                    Common.DateFormat(new Date(), "yyyy-MM-dd hh:mm:ss") +
                    " </span>" +
                    '<span class="message-content">' +
                    message +
                    "</span>" +
                    "</div>" +
                    "</div>";
            $("#divMessages").append(htmlStr1);
            gotoEnd();
        },
        UpdateContactsComplete: function () {
            initializeUsers();
            alert("请求好友列表成功，可以进行通信了！");
        },
        BrowserError: function () {
            alert("当前浏览器不支持通信组件，请切换浏览器或兼容/极速模式！");
        },
        OnOpened: function (e) {
            console.info(e);
            alert("启动通信组件成功，正在登陆系统……");
            socket.SendUserInfo(jQuery("#userName").val(), jQuery("#userPwd").val());
        },
        OnError: function (e) {
            console.log(e);
            alert("通信程序发生错误！请按 F12 查看！");
        }
    });

    /**
     * 点击登录按钮
     */
    jQuery("#loginServer").click(function () {
        var ip = jQuery("#serverIp").val();
        if (ip.trim() === "" || !Common.IsIp(ip)) {
            layer.ready(function () {
                layer.tips("Ip 地址有误！", "#serverIp",
                {
                    tips: [3, "#FF0000"],
                    time: 4000
                });
            });
            //$.messager.alert("提示")
            return;
        }
        var portStr = jQuery("#serverPort").val();
        var port = Number(portStr);
        if (portStr.trim() === "" || port > 65535 || port < 0) {
            layer.ready(function () {
                layer.tips("端口号有误！", "#serverPort",
                {
                    tips: [3, "#FF0000"],
                    time: 4000
                });
            });
            return;
        }
        var name = jQuery("#userName").val();
        if (name.trim() === "") {
            layer.ready(function () {
                layer.tips("请填写用户名！", "#userName",
                {
                    tips: [3, "#FF0000"],
                    time: 4000
                });
            });
            return;
        }
        socket.Initialize(ip, port);
    });

    /**
     * 点击关闭按钮
     */
    $("#logoutServer").click(function () {
        socket.Stop();
    });

    /**
     * 点击发送消息按钮
     */
    $("#buttonSendMessage").click(function () {
        var sendMess = $("#textareaSendMessage").val();
        if (sendMess === "") {
            layer.ready(function () {
                layer.msg("没有发送内容哦！");
            });
            return;
        }
        if (socket.UserInfo == undefined || chatingUserId == undefined) {
            layer.ready(function () {
                layer.msg("没有联系人哦！");
            });
            return;
        }
        var user = socket.GetUserById(chatingUserId);
        if (user == undefined) {
            layer.ready(function () {
                layer.msg("聊天对象已经下线了！");
            });
            return;
        }
        socket.SendTextMessage(chatingUserId, sendMess);
        var htmlStr1 =
            '<div class="chat-message">\r\n<img class="message-avatar" src="../Images/TouXiang.jpg" alt="">\r\n<div class="message">\r\n<a class="message-author" href="#"> 我</a> 对 ' + user.Name + ' 说：\r\n<span class="message-date"> ' + Common.DateFormat(new Date(), "yyyy-MM-dd hh:mm:ss") + ' </span>\r\n<span class="message-content">\r\n' + sendMess + "\r\n</span>\r\n</div>\r\n</div>";
        $("#divMessages").append(htmlStr1);
        $("#textareaSendMessage").val("");
        gotoEnd();

    });

    /**
     * 点击广播按钮
     */
    $("#buttonBroadcastMessage").click(function () {
        var sendMess = $("#textareaSendMessage").val();
        if (sendMess === "") {
            layer.ready(function () {
                layer.alert("没有发送内容哦！");
            });
            return;
        }
        socket.BroadcastTextMessage(sendMess);
        var htmlStr1 = '<div class="chat-message">' +
            '<img class="message-avatar" src="../Images/TouXiang.jpg" alt="">' +
            '<div class="message">' +
            '<a class="message-author" href="#"> 我</a> 对所有人说：' +
            '<span class="message-date"> ' +
            Common.DateFormat(new Date(), "yyyy-MM-dd hh:mm:ss") +
            " </span>" +
            '<span class="message-content">' +
            sendMess +
            "</span>" +
            "</div>" +
            "</div>";
        $("#divMessages").append(htmlStr1);
        $("#textareaSendMessage").val("");
        gotoEnd();
    });

    /**
     * 初始化好友列表
     * @returns {} 
     */
    function initializeUsers() {
        $("#divUsers").empty();
        for (var i = 0; i < socket.Contacts.length; i++) {
            if (socket.Contacts[i].Id === socket.UserInfo.Id) {
                continue;
            }
            var strHtml = '<div id="' +
                socket.Contacts[i].Id +
                '" class="chat-user">' +
                '<img class="chat-avatar" src="../Images/TouXiang.jpg" alt="">' +
                '<div class="chat-user-name">' +
                '<a href="#" onclick="setChatingUser(\'' +
                socket.Contacts[i].Id +
                '\')">' +
                socket.Contacts[i].Name +
                "</a>" +
                "</div>" +
                "</div>";
            $("#divUsers").append(strHtml);
        }
        if (chatingUserId != undefined) {
            var user = socket.GetUserById(chatingUserId);
            if (user == undefined) {
                chatingUserId = undefined;
                $("#divUserChating").empty();
            }
        }
    }

    /**
     * 快捷键绑定
     * @param {} e 
     * @returns {} 
     */
    document.onkeydown = function (e) {
        var theEvent = window.event || e;
        var keyCode = theEvent.keyCode || theEvent.which;
        var ctrKey = e.ctrlKey || e.metaKey;
        if (!ctrKey && keyCode === 13) {
            $("#buttonSendMessage").click();
        } else if (ctrKey && keyCode === 13) {
            $("#buttonBroadcastMessage").click();
        }
    }
});

/**
 * 设置最后一条消息的时间
 * @returns {} 
 */
function setLastTime() {
    document.getElementById("lastTime").innerText = Common.DateFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
}

/**
 * 滚动消息列表到最后一条
 * @returns {} 
 */
function gotoEnd() {
    var divElement = document.getElementById("divMessages");
    divElement.scrollTop = divElement.scrollHeight;
    setLastTime();
}

/**
 * 设置当前正在聊天的对象
 * @param {} id 标识
 * @returns {} 
 */
function setChatingUser(id) {
    chatingUserId = id;
    var user = socket.GetUserById(chatingUserId);
    var strHtml = '<div class="chat-user">' +
        '<span class="pull-right label label-primary">正在聊天</span>' +
        '<img class="chat-avatar" src="../Images/TouXiang.jpg" alt="">' +
        '<div class="chat-user-name">' +
        '<a href="#">' +
        user.Name +
        "</a>" +
        "</div>" +
        "</div>";
    $("#divUserChating").html(strHtml);
}

/**
 * 当前正在聊天对象的标识
 */
var chatingUserId = undefined;